package com.ojoin.trade.common.utils.excel;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import com.ojoin.trade.common.utils.CommonUtils;
import com.ojoin.trade.common.utils.file.FileUtilsJoin;

public class Excel2003Writer {

	/**
	 * 写入excel并填充内容,一个sheet只能写65536行以下，超出会报异常，写入时建议使用AbstractExcel2007Writer
	 * 
	 * @param fileName
	 * @throws IOException
	 */
	public static void writeExcel(String fileName) throws IOException {

		// 创建excel2003对象
		Workbook wb = new HSSFWorkbook();

		// 设置文件放置路径和文件名
		FileOutputStream fileOut = new FileOutputStream(fileName);
		// 创建新的表单
		Sheet sheet = wb.createSheet("newsheet");
		// 创建新行
		for (int i = 0; i < 20000; i++) {
			Row row = sheet.createRow(i);
			// 创建单元格
			Cell cell = row.createCell(0);
			// 设置单元格值
			cell.setCellValue(1);
			row.createCell(1).setCellValue(1 + i);
			row.createCell(2).setCellValue(true);
			row.createCell(3).setCellValue(0.43d);
			row.createCell(4).setCellValue('d');
			row.createCell(5).setCellValue("");
			row.createCell(6).setCellValue("第七列" + i);
			row.createCell(7).setCellValue("第八列" + i);
		}
		wb.write(fileOut);
		fileOut.close();
	}

	public static void writeExcelAppend(String fileName, List<List<String>> list)
			throws IOException {

		if(CommonUtils.isEmpty(list)){
			return ;
		}
		
		Workbook web ;
		Sheet  sheet;
		FileOutputStream out;
		File file=  new File(fileName);
		if(!file.exists()){

			web = new HSSFWorkbook();
			sheet = web.createSheet("newsheet");
			// 设置文件放置路径和文件名
			out = new FileOutputStream(fileName);
			// 创建新的表单
			
		}else {
			
			InputStream in = new FileInputStream(fileName);
			POIFSFileSystem fs1 = new POIFSFileSystem(in);
			web = new HSSFWorkbook(fs1);
			sheet = web.getSheetAt(0);
			
			
			//in.close();
			
			
			out = new FileOutputStream(fileName);
			
			
		}
		
		
		
		int old = sheet.getLastRowNum()+1;
		
		int rownum = old+list.size();
		// 创建excel2003对象

		// 设置文件放置路径和文件名
		

		// 创建新行
		for (int i = old; i < rownum; i++) {
			Row row = sheet.createRow(i);
			
			List<String> li = list.get(i-old);
			
			int m = row.getLastCellNum();
			
			if(m < 0 ){
				m = 0 ;
			}
			for(;m<li.size();m++){
				
				row.createCell(m).setCellValue(li.get(m));

			}

		}
		out.flush();
		web.write(out);
		out.close();
	}

}
